const Comment = require('../models/Comment');
const Article = require('../models/Article');

// 添加评论
exports.addComment = async (req, res) => {
  try {
    const { content } = req.body;
    const articleId = req.params.id;
    
    // 检查文章是否存在
    const article = await Article.findById(articleId);
    if (!article) {
      return res.status(404).json({ message: '文章不存在' });
    }
    
    const newComment = new Comment({
      content,
      article: articleId,
      author: req.userId
    });
    
    const comment = await newComment.save();
    res.status(201).json(comment);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取文章的所有评论
exports.getComments = async (req, res) => {
  try {
    const article = await Article.findById(req.params.id);
    if (!article) {
      return res.status(404).json({ message: '文章不存在' });
    }
    
    const comments = await Comment.find({ article: req.params.id })
      .populate('author', 'username email');
    
    res.json(comments);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};